<?php

namespace app\admin\model;

use think\Model;


class Order extends Model
{


  // 表名
  protected $name = 'order';

  // 自动写入时间戳字段
  protected $autoWriteTimestamp = 'integer';

  // 定义时间戳字段名
  protected $createTime = 'createtime';
  protected $updateTime = 'updatetime';
  protected $deleteTime = false;

  // 追加属性
  protected $append = [
    'status_text',
    'room',
    'user'
  ];

  public static function init()
  {
    self::beforeInsert(function ($row) {
      Room::update(['status' => ['预定中']], ['id' => $row->room_id]);
    });
    self::beforeUpdate(function ($row) {
      $changed = $row->getChangedData();
      if (isset($changed['status'])) {
        if ($row->status == '入住中') {
          Room::update(['status' => ['入住中']], ['id' => $row->room_id]);
        }
        if ($row->status == '取消') {
          Room::update(['status' => ['未使用']], ['id' => $row->room_id]);
        }
        if ($row->status == '完成') {
          Room::update(['status' => ['清洁中']], ['id' => $row->room_id]);
        }
      }
    });
  }


  public function getStatusList()
  {
    return ['预定中' => __('预定中'), '完成' => __('完成'), '取消' => __('取消')];
  }


  public function getStatusTextAttr($value, $data)
  {
    $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
    $list = $this->getStatusList();
    return isset($list[$value]) ? $list[$value] : '';
  }

  public function room()
  {

    return $this->belongsTo(Room::class, 'room_id', 'id');
  }

  public function user()
  {

    return $this->belongsTo(User::class, 'user_id', 'id');
  }

}
